// @flow
import React from 'react'
import { Link, Switch, Route } from 'react-router-dom'
import Sidebar from 'containers/SidebarContainer'
import { Menu, Icon } from 'antd'

const SubMenu = Menu.SubMenu

type Props = {
  id: string,
  menu: Object,
  style: Object,
  routes: Array<Object>
}

// let key = 0
type States = {
  currentKey: string
}
export default class MenuSideBar extends React.Component {
  props: Props
  state: States
  clickMenu: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      currentKey: ''
    }
    this.clickMenu = this.clickMenu.bind(this)
  }

  componentWillMount () {
    const location = window.location
    const { menu } = this.props
    Object.keys(menu).map((d, i) => {
      menu[d].map((item, index) => {
        if (location.pathname === item[1] || location.pathname.indexOf(item[1]) > -1) {
          this.setState({
            currentKey: item[1]
          })
        }
      })
    })
  }

  clickMenu (e: Object) {
    this.setState({
      currentKey: e.key
    })
  }
  render () {
    const { menu, routes } = this.props
    const { currentKey } = this.state
    return (
      <div style={{ height: '100%' }}>
        <Sidebar id='menuSidebar'
          style={{ width: '300px' }} type='float'>
          <Menu
            style={{ width: 300, height: '100%' }}
            defaultSelectedKeys={[currentKey]}
            selectedKeys={[currentKey]}
            onClick={this.clickMenu}
            defaultOpenKeys={
              Object.keys(menu).map((d, i) => {
                return i + ''
              })
            }
            mode='inline'
          >
            {
              Object.keys(menu).map((d, i) => {
                let dom = []
                menu[d].map((item, index) => {
                  const url = item[1]
                  dom.push(<Menu.Item key={item[1]}>
                    <Link to={url}>
                      {item[0]}
                    </Link>
                  </Menu.Item>)
                })
                return (
                  <SubMenu key={i} title={<span><Icon type='bars' /><span>{d}</span></span>}>
                    {
                      dom.map((d, i) => { return d })
                    }
                  </SubMenu>
                )
              })
            }
          </Menu>
        </Sidebar>
        <Switch>
          {
            Object.keys(menu).map((d, i) => {
              return menu[d].map((item, index) => {
                return <Route key={index} exact={item[3] === 'exact'}
                  path={item[1]}
                  component={item[2]} />
              })
            })
          }
          {
            routes && routes.length > 0 && routes.map((d, i) => {
              return d
            })
          }
        </Switch>
      </div>
    )
  }
}
